import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/user.dart';
import 'package:flutter_house_manager/components/CameraDialog.dart';
import 'package:flutter_house_manager/utils/toast.dart';
import 'package:get/get.dart' hide FormData, MultipartFile;
import 'package:image_picker/image_picker.dart';
import '../../controller/user_info_controller.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  // 1. 引入UserInfoController
  UserInfoController userInfoController = Get.find<UserInfoController>();
  // 昵称控制器
  TextEditingController nickController = TextEditingController();
  // 临时图片地址
  String tempAvatar = '';
  String tempFileName = '';

  /// ---------------------------------------
  // 2. 初始化昵称控制器
  @override
  void initState() {
    super.initState();
    nickController.text = userInfoController.userInfo['nickName'] ?? '';
  }

  Widget getAvatar() {
    // 判断用户是否已经选择了头像
    if (tempAvatar.isNotEmpty) {
      // 判断是否是web端
      if (kIsWeb) {
        return Image.network(
          tempAvatar,
          width: 30,
          height: 30,
          fit: BoxFit.cover,
        );
      } else {
        // 移动端使用file文件显示图片
        return Image.file(
          File(tempAvatar),
          width: 30,
          height: 30,
          fit: BoxFit.cover,
        );
      }
    }

    if (userInfoController.userInfo["avatar"] != "" &&
        userInfoController.userInfo["avatar"] != null) {
      return Image.network(
        userInfoController.userInfo["avatar"],
        width: 30,
        height: 30,
        fit: BoxFit.cover,
      );
    }
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 30,
      height: 30,
    );
  }

  // 保存用户信息
  saveUserInfo() async {
    // 1. 获取用户输入的昵称
    String nickName = nickController.text;
    // 2. 内容校验
    if (nickName.isEmpty) {
      PromptAction.showWarning('昵称不能为空');
      return;
    }
    // 2.3 昵称只能输入中文，长度在2-10个字符之间
    if (!RegExp(r'^[\u4e00-\u9fa5]{2,10}$').hasMatch(nickName)) {
      PromptAction.showWarning('请输入在2-10字符之间的中文');
      return;
    }

    /// ------------------------------------
    String avatar = userInfoController.userInfo['avatar'] ?? '';
    if (tempAvatar.isNotEmpty) {
      FormData data;
      // 如果是web端
      if (kIsWeb) {
        // 1. 根据图片的临时路径得到二级制文件
        Uint8List list = await XFile(tempAvatar).readAsBytes();
        // 2. 获取文件对象
        MultipartFile file = MultipartFile.fromBytes(
          list,
          filename: tempFileName,
        );
        // 3. 创建FormData对象
        data = FormData.fromMap({
          'file': file,
          "type": "avatar",
        });
      } else {
        data = FormData.fromMap({
          'file': MultipartFile.fromFileSync(tempAvatar),
          "type": "avatar",
        });
      }

      // 4. 调用接口
      final res = await uploadPhotoAPI(data);
      avatar = res['url'];
    }

    /// -----------------------------------
    // 3. 调用接口
    await updateUserInfoAPI({
      'nickName': nickName,
      'avatar': avatar,
    });
    tempAvatar = '';
    tempFileName = '';
    // 4. 提示保存成功
    PromptAction.showSuccess('保存成功');
    // 5. 同步Getx信息
    userInfoController.userInfo['nickName'] = nickName;
    userInfoController.userInfo['avatar'] = avatar;
    userInfoController.update();
    // 6. 返回
    Navigator.of(context).pop();
  }

  // 打开相册获取图片
  openLibrary() async {
    // 1. 创建一个选择图片的实例
    ImagePicker picker = ImagePicker();
    // 2. 调用方法打开相册
    // ImageSource.gallery 获取相册图片
    // ImageSource.camera 获取相机图片
    XFile? file = await picker.pickImage(source: ImageSource.gallery);
    // 3. 判断图片是否获取成功
    if (file != null) {
      PromptAction.showSuccess('获取相册图片成功');
      // PromptAction.showSuccess(file.path);

      // 4. 存储图片地址和名称
      tempAvatar = file.path;
      tempFileName = file.name;
      // 5. 刷新页面
      setState(() {});

      Navigator.of(context).pop();
    }
  }

  /// 拍照
  openCamera() async {
    // 1. 创建一个选择图片的实例
    ImagePicker picker = ImagePicker();
    // 2. 调用方法打开相册
    // ImageSource.gallery 获取相册图片
    // ImageSource.camera 获取相机图片
    XFile? file = await picker.pickImage(source: ImageSource.camera);
    // 3. 判断图片是否获取成功
    if (file != null) {
      PromptAction.showSuccess('获取相机图片成功');
      // PromptAction.showSuccess(file.path);

      // 4. 存储图片地址和名称
      tempAvatar = file.path;
      tempFileName = file.name;
      // 5. 刷新UI
      setState(() {});

      Navigator.of(context).pop();
    }
  }

  /// ---------------------------------------

  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserInfoController>(builder: (controller) {
      return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('个人信息'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: [
                  const Text(
                    '头像',
                    style: TextStyle(fontSize: 16),
                  ),
                  const Spacer(),
                  Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          // showSheet();
                          showCameraDialog(context, onLibrary: () {
                            openLibrary();
                          }, onCamera: () {
                            openCamera();
                          });
                        },
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: getAvatar(),
                        ),
                      ),
                      const Icon(Icons.arrow_forward_ios, size: 12)
                    ],
                  )
                ],
              ),
            ),
            Row(
              children: [
                const Text('昵称'),
                const Spacer(),
                Expanded(
                  child: TextField(
                    controller: nickController,
                    decoration: const InputDecoration(
                      hintText: '请输入昵称',
                      border: InputBorder.none,
                    ),
                    textAlign: TextAlign.right,
                  ),
                ),
                const Icon(Icons.arrow_forward_ios, size: 12)
              ],
            ),
            const SizedBox(
              height: 20,
            ),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      saveUserInfo();
                    },
                    child: const Text(
                      '保存',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      );
    });
  }
}
